class EventEmitter {
  constructor() {
    this.events = {};
  }

  //   订阅
  on(event, listener) {
    if (!this.events[event]) {
      this.events[event] = [];
    }
    this.events[event].push(listener);
  }

  //   触发事件
  emit(event, ...args) {
    if (this.events[event]) {
      this.events[event].forEach((listener) => listener(...args));
    }
  }

  //   取消订阅
  off(event, listener) {
    if (this.events[event]) {
      this.events[event] = this.events[event].filter((l) => l !== listener);
    }
  }

  //   只触发一次的订阅
  once(event, listener) {
    const fn = (...args) => {
      listener(...args);
      this.off(event, fn);
    };
    this.on(event, fn);
  }
}

const emitter = new EventEmitter();

// 订阅事件
function onMessageReceived(data) {
  console.log('Message received:', data);
}

emitter.on('message', onMessageReceived);

// 发布事件
emitter.emit('message', 'Hello, world!');

// 取消订阅
emitter.off('message', onMessageReceived);

// 再次发布事件，取消订阅后不会执行回调
emitter.emit('message', 'This will not be logged');

// 只触发一次的订阅
emitter.once('onceMessage', (data) => {
  console.log('This will be logged once:', data);
});

emitter.emit('onceMessage', 'Once!');
emitter.emit('onceMessage', 'This will not be logged.');
